package ru.ifmo.metopt;

import org.springframework.beans.factory.annotation.Required;
import ru.ifmo.metopt.abstracts.Factory;
import ru.ifmo.metopt.abstracts.Function;
import ru.ifmo.metopt.abstracts.GradientEncounter;

/**
 * @author avhaliullin
 */
public class SimpleGradientEcounter implements GradientEncounter {
    private Factory<Double> dxProvider;

    @Override
    public double[] gradient(Function f, double[] point) {
        double dx = dxProvider.create();

        double[] grad = new double[point.length];
        double fx = f.f(point);
        for (int i = 0; i < point.length; i++) {
            point[i] += dx;
            grad[i] = (f.f(point) - fx) / dx;
            point[i] -= dx;
        }
        return grad;
    }

    @Required
    public void setDxProvider(Factory<Double> dxProvider) {
        this.dxProvider = dxProvider;
    }
}
